﻿using System;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using System.Data;
using System.Drawing;
using HRM.BusinessLogic;
using System.Collections.Generic;
using FormCommon;

namespace HRM
{
    public partial class frmEmployee_QTChucDanh_Edit : FormBase
    {
        PremiumInfo _PremiumInfo;
        PremiumClient _wcfPremium;
        EmployeeClient _wcfEmployee;
        DetailClient _wcfDetail;
        DetailInfo _DetailInfo;

        int _EmployeeID;
        bool isChange = false;
        DialogResult dlgResult;
        int _DetailID = 0;
        public delegate void AfterCreateOrSaveItem();
        public event AfterCreateOrSaveItem AfterCreateEvent;

        public frmEmployee_QTChucDanh_Edit(string _InsBookNo)
        {
            InitializeComponent();
            dlgResult = DialogResult.Cancel;

            _wcfPremium = Service.Premium();
            _wcfEmployee = Service.Employee();

            txtDateVal.ReadOnly = true;
            txtDateVal.BackColor = Color.White;
            DateTextBoxShort dtbFrom = new DateTextBoxShort(mtxFromDate);
            DateTextBoxShort dtbTo = new DateTextBoxShort(mtxToDate);

            //-------------------------------------------------------------------
            txtSIBookNo.Text = _InsBookNo;
            timSoBHXH1.Text = txtSIBookNo.Text;
            timSoBHXH1.Tag = timSoBHXH1.Text;
            timSoBHXH1.SelectAll();
            txtDateVal.Text = DateTime.Now.ToString("dd/MM/yyyy");

            //
            dgvQTBHXH.AutoGenerateColumns = dgvDieuChinh.AutoGenerateColumns = false;
            //
            AddColumnChucDanh();
            AddColumnDieuChinh();
            //

            TabOrderManager tom = new TabOrderManager(this);
            tom.SetTabOrder(TabOrderManager.TabScheme.AcrossFirst);

            this.KeyDown += new KeyEventHandler(frmEmployee_QTChucDanh_Edit_KeyDown);

            //timSoBHXH1_Validated(null, null);
            LoadData();

            //
            if (dgvQTBHXH.Rows.Count > 0)
            {
                mtxFromDate.Text = Globals.Object_GetValue<DateTime>(dgvQTBHXH.Rows[0].Cells["Premium_FromDate"].Value).ToString("MM/yyyy");

                if (dgvQTBHXH.Rows.Count > 1)
                {
                    mtxToDate.Text = Globals.Object_GetValue<DateTime>(dgvQTBHXH.Rows[dgvQTBHXH.Rows.Count - 1].Cells["Premium_ToDate_Chuan"].Value).ToString("MM/yyyy");
                }
            }
        }

        void frmEmployee_QTChucDanh_Edit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Control controlObj = ((System.Windows.Forms.Form)sender).ActiveControl;
                string controlType = controlObj.GetType().Name;
                if ("TextBox,ComboBox,RadioButton,CheckBox".Contains(controlType))
                {
                    if (controlType == "TextBox" && ((TextBox)controlObj).Multiline)
                        return;

                    

                    //Focus tới control tiếp theo
                    if (((System.Windows.Forms.Form)sender).SelectNextControl(((System.Windows.Forms.Form)sender).ActiveControl, true, true, true, true))
                    {
                        //
                        if (((System.Windows.Forms.Form)sender).ActiveControl is TextBox)
                        {
                            (((System.Windows.Forms.Form)sender).ActiveControl as TextBox).SelectAll();
                        }
                    }
                    //
                    e.Handled = true;
                    e.SuppressKeyPress = true; //bỏ tiếng kêu DING
                }
            }
        }

        public DialogResult Show_Form()
        {
            //return this.ShowDialog();

            
            this.Show();
            return DialogResult.Cancel;
        }

        protected override void Init_Control()
        {
            base.Init_Control();
            
        }

        private void AddColumnChucDanh()
        {
            dgvQTBHXH.Columns.Clear();
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_WorkUnit", UpdateUI.GetString("donvilamviec"), "", 90, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_FromDate", "Từ tháng", "C", 80, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_ToDate_Chuan", "Đến tháng", "C", 80, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_Job", UpdateUI.GetString("nghenghiep"), "", 100, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "LoaiPs", "Loại", "C", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_Salary", "ML", "R", 70, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_BasicFactor", "HSL", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_PositionFactor", "HS Cvụ", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_SeniorityFactorPercent", "% TNNghề", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_SeniorityFactor", "HS TNNghề", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_OverSeniorityFactorPercent", "% TNVK", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_OverSeniorityFactor", "HS TNVK", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_AreaFactor", "HS KV", "R", 60, false, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_MonthNo", "Số tháng", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "PA", "PA", "R", 60, true, true);
            UISetting.AddColumn(ref dgvQTBHXH, "Premium_Description", UpdateUI.GetString("ghichu"), "", 100, false, true);
        }

        DataGridHandle m_GridHandle;
        private void AddColumnDieuChinh()
        {
            dgvDieuChinh.Columns.Clear();
            //UISetting.AddColumn(ref dgvDieuChinh, "Detail_InputDate", "Ngày nhập", "C", 80, true, true);
            //UISetting.AddColumn(ref dgvDieuChinh, "Detail_FromDate", "Từ tháng", "C", 80, true, true);
            //UISetting.AddColumn(ref dgvDieuChinh, "Detail_ToDate", "Đến tháng", "C", 80, true, true);
            //UISetting.AddColumn(ref dgvDieuChinh, "Detail_PositionName", UpdateUI.GetString("nghenghiep"), "", 100, true, true);
            //UISetting.AddColumn(ref dgvDieuChinh, "Detail_Description", UpdateUI.GetString("ghichu"), "", 100, false, true);
            //UISetting.AddColumn(ref dgvDieuChinh, "Detail_InstypeCode", "PA", "R", 60, true, true);

            List<DataGridViewColumn> arrColumn = new List<DataGridViewColumn>();
            //arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Họ và tên", "Employee_FullName", 120));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ID", "Detail_Id", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Từ tháng", "Detail_FromDate", 70, Globals.CS_DISPLAY_MONTHYEAR_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Đến tháng", "Detail_ToDate", 70, Globals.CS_DISPLAY_MONTHYEAR_FORMAT));
            //arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số tháng", "Detail_TotalMonth", 60));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Chức vụ", "Detail_PositionName", 120));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("PA", "Detail_InsTypeCode", 40));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày nhập", "Detail_InputDate", 80));
            
            m_GridHandle = FormGlobals.Grid_Init(dgvDieuChinh, arrColumn, "", 1);
        }

        private void LoadData()
        {
            LoadQTBH(txtSIBookNo.Text, Program.strBranchCode);
            LoadDieuChinh(txtSIBookNo.Text, Program.strBranchCode);
        }

        private void LoadQTBH(string _InsBookNo, string _BranchCode)
        {
            FormGlobals.App_ProgressShow(delegate()
            {
                try
                {
                    DataTable dt = new DataTable();
                    PremiumClient _wcfPremium = Service.Premium();
                    int _opt = 0;
                    dt = _wcfPremium.Premium_QTBH(Program.strBranchCode, _InsBookNo, _opt, DateTime.MinValue, DateTime.MaxValue, 0).Tables[0];
                    dgvQTBHXH.Rows.Clear();
                    if (dt != null)
                    {



                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            dgvQTBHXH.Rows.Insert(i, 1);
                            dgvQTBHXH.Rows[i].Cells["Premium_WorkUnit"].Value = dt.Rows[i]["Premium_WorkUnit"].ToString();
                            dgvQTBHXH.Rows[i].Cells["Premium_FromDate"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_FromDate"]).ToString("MM/yyyy");
                            //--dgvPremium_QTBHXH.Rows[i].Cells["Premium_ToDate"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_ToDate"]).ToString("MM/yyyy");
                            dgvQTBHXH.Rows[i].Cells["Premium_ToDate_Chuan"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_ToDate_Chuan"]).ToString("MM/yyyy");
                            


                            
                            dgvQTBHXH.Rows[i].Cells["LoaiPs"].Value = dt.Rows[i]["LoaiPs"].ToString();
                            dgvQTBHXH.Rows[i].Cells["Premium_Job"].Value = dt.Rows[i]["Premium_Job"].ToString();
                            dgvQTBHXH.Rows[i].Cells["Premium_Salary"].Value = dt.Rows[i]["Premium_Salary"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_Salary"]).ToString("#,##0");
                            dgvQTBHXH.Rows[i].Cells["Premium_BasicFactor"].Value = dt.Rows[i]["Premium_BasicFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_BasicFactor"]).ToString("#0.0##");
                            dgvQTBHXH.Rows[i].Cells["Premium_PositionFactor"].Value = dt.Rows[i]["Premium_PositionFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_PositionFactor"]).ToString("#0.0##");

                            dgvQTBHXH.Rows[i].Cells["Premium_SeniorityFactor"].Value = dt.Rows[i]["Premium_SeniorityFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_SeniorityFactor"]).ToString("#0.0##");

                            dgvQTBHXH.Rows[i].Cells["Premium_OverSeniorityFactor"].Value = dt.Rows[i]["Premium_OverSeniorityFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_OverSeniorityFactor"]).ToString("#0.0##");

                            dgvQTBHXH.Rows[i].Cells["Premium_AreaFactor"].Value = dt.Rows[i]["Premium_AreaFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_AreaFactor"]).ToString("#0.0##");
                            if (dt.Rows[i]["Premium_MonthNo"].ToString() != "0")
                                dgvQTBHXH.Rows[i].Cells["Premium_MonthNo"].Value = dt.Rows[i]["Premium_MonthNo"].ToString();
                            else
                                dgvQTBHXH.Rows[i].Cells["Premium_MonthNo"].Value = (UISetting.GetMonth(Convert.ToDateTime(dt.Rows[i]["Premium_FromDate"]), Convert.ToDateTime(dt.Rows[i]["Premium_ToDate_Chuan"])) + 1).ToString();

                            string PA = dt.Rows[i]["Detail_InsTypeCode"].ToString();
                            PA = "ON,TS,OF".IndexOf(PA) > 0 ? PA : "";
                            dgvQTBHXH.Rows[i].Cells["PA"].Value = PA;
                            dgvQTBHXH.Rows[i].Cells["Premium_Description"].Value = dt.Rows[i]["Premium_Description"].ToString();
                            if (dgvQTBHXH.Rows[i].Cells["Premium_WorkUnit"].Value.ToString() == "")
                            {
                                dgvQTBHXH.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                                dgvQTBHXH.Rows[i].DefaultCellStyle.SelectionBackColor = Color.Yellow;
                            }

                            //Tính % nghề, vk

                            decimal BasicFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_BasicFactor"].Value.ToString());
                            decimal PosionFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_PositionFactor"].Value.ToString());
                            decimal OverFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_OverSeniorityFactor"].Value.ToString());
                            decimal JobFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_SeniorityFactor"].Value.ToString());
                            //
                            if (OverFactor != 0)
                            {
                                decimal OverFactor_Percent = (OverFactor * 100 / BasicFactor);
                                dgvQTBHXH.Rows[i].Cells["Premium_OverSeniorityFactorPercent"].Value = Math.Round(OverFactor_Percent).ToString();
                            }
                            if (JobFactor != 0)
                            {
                                decimal JobFactor_Percnet = (JobFactor * 100 / (BasicFactor + PosionFactor + OverFactor));
                                dgvQTBHXH.Rows[i].Cells["Premium_SeniorityFactorPercent"].Value = Math.Round(JobFactor_Percnet).ToString();
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
                }
            }, "Lấy dữ liệu");
        }

        private void LoadDieuChinh(string _InsBookNo, string _BranchCode)
        {
            DataTable dtChucDanh = Employee_Controller.Instance().Employee_DSChuDanh(
                        Program.strBranchCode
                        , _InsBookNo
                        , 0
                        , 0);
            //
            dgvDieuChinh.DataSource = dtChucDanh;
        }


        bool CheckValid()//kiểm tra dữ liệu nhập
        {
            if (String.IsNullOrEmpty(txtSIBookNo.Text))
            {
                MessageBox.Show("Số sổ BHXH không hợp lệ");
                return false;
            }
            if (!CheckTextValid.IsDateTime(mtxFromDate.Text, "MM/yyyy"))
            {
                mtxFromDate.Focus();
                MessageBox.Show(UpdateUI.GetString("ngaybatdaukhonghople"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (!CheckTextValid.IsDateTime(mtxToDate.Text, "MM/yyyy"))
            {
                mtxToDate.Focus();
                MessageBox.Show(UpdateUI.GetString("ngayketthuckhonghople"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (DateTime.Compare(UISetting.GetDate(mtxFromDate.Text), UISetting.GetDate(mtxToDate.Text)) > 0)
            {
                mtxFromDate.Focus();
                MessageBox.Show(UpdateUI.GetString("ngayketthucphaimuonhonngaybatdau"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValid())
            {
                isChange = true;
                return;
            }
            //
            Save_Data();

            DateTime _toDate = DateTime.ParseExact(mtxToDate.Text, "MM/yyyy", null);
            mtxFromDate.Text = _toDate.AddMonths(1).ToString("MM/yyyy");
            mtxToDate.Text = "";
            txtJob.Text = "";
            //
            LoadData();
            //
            mtxToDate.SetFocus_SelectAll();
        }

        private void Save_Data()
        {
            DateTime fromDate = DateTime.ParseExact(mtxFromDate.Text, "MM/yyyy", null);
            DateTime toDate = DateTime.ParseExact(mtxToDate.Text, "MM/yyyy", null);

            Employee_Controller.Instance().Employee_UpdateChucDanh(0, Program.strBranchCode,  txtSIBookNo.Text, fromDate, toDate, txtJob.Text);
        }

        private void btnNew_Click(object sender, EventArgs e)
        {

        }

        private void frmPremiumInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (isChange)
            //{
            //    if (MessageBox.Show(UpdateUI.GetString("bandathaydoidulieu") + "\n" + UpdateUI.GetString("coluutruockhithoatkhong"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            //    {
            //        btnSave_Click(null, null);
            //        if (isChange)
            //            e.Cancel = true;
            //        else
            //            e.Cancel = false;
            //    }
            //}
            //_wcfPremium.Close();
            //this.DialogResult = dlgResult;
        }

        private void frmPremiumInfo_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    break;
                case Keys.Escape:
                    this.Close();
                    break;
                case Keys.F2:
                    btnSaveAndNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnSave_Click(null, null);
                    break;
            }
        }

        private void txtMonthNo_Leave(object sender, EventArgs e)
        {
            lblMonth.Text = UISetting.GetIntNo(lblMonth.Text).ToString();
        }

        private void DataChange(object sender, EventArgs e)
        {
            isChange = true;
        }

        private void mtxToDate_Validated(object sender, EventArgs e)
        {
            if (mtxToDate.Text.Trim() != "")
            {
                if (mtxToDate.Text != "  /")
                    if (!CheckTextValid.IsDateTime(mtxFromDate.Text, "MM/yyyy"))
                    {
                        mtxFromDate.Focus();
                        MessageBox.Show(UpdateUI.GetString("ngaybatdaukhonghople"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else if (!CheckTextValid.IsDateTime(mtxToDate.Text, "MM/yyyy"))
                    {
                        mtxToDate.Focus();
                        MessageBox.Show(UpdateUI.GetString("ngayketthuckhonghople"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else
                    {
                        DateTime _date1 = DateTime.ParseExact(mtxFromDate.Text, "MM/yyyy", null);
                        DateTime _date2 = DateTime.ParseExact(mtxToDate.Text, "MM/yyyy", null);
                        lblMonth.Text = (UISetting.GetMonth(_date1, _date2) + 1).ToString();
                    }
            }
        }

        private void btnSaveAndNew_Click(object sender, EventArgs e)
        {
            btnSave_Click(null, null);
            mtxFromDate.Text = "";// _toDate.AddMonths(1).ToString("MM/yyyy");
            mtxToDate.Text = "";

            if (AfterCreateEvent != null)
                AfterCreateEvent();
            //
            mtxFromDate.Focus();
        }

        //Kiểm tra thay đổi số sổ thì load lại danh sách quá trình trước đây
        private void timSoBHXH1_Validated(object sender, EventArgs e)
        {
            if (Globals.Object_GetString(timSoBHXH1.Tag, "") != timSoBHXH1.Text && timSoBHXH1.Text != ""
                && timSoBHXH1.EmployeeId > 0
                )
            {
                FormGlobals.App_ProgressShow(delegate()
                {
                    txtSIBookNo.Text = timSoBHXH1.Text;
                    txtEmployee_FullName.Text = timSoBHXH1.EmployeeName;
                    LoadData();
                    mtxFromDate.SetFocus_SelectAll();
                }, "Loading");
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if(dgvDieuChinh.SelectedRows.Count ==0)
            {
                FormGlobals.Message_Information("Không có bản ghi điều chỉnh chức danh nào được chọn để xóa");
                return;
            }
            //
            if(FormGlobals.Message_Confirm("Bạn có chắc chắn muốn xóa bản ghi điều chỉnh chức danh đã chọn?"))
            {
                foreach (DataGridViewRow dgrv in dgvDieuChinh.SelectedRows)
                {
                    int Detail_Id = Globals.Object_GetValue<int>(dgrv.Cells["Detail_Id"].Value);
                    Detail_Controller.Instance().Detail_Delete(Detail_Id,0);
                }
                //
                LoadData();
            }
        }

        private void btnNew_Click_1(object sender, EventArgs e)
        {
            timSoBHXH1.Text = "";
            timSoBHXH1.EmployeeId = 0;
            txtSIBookNo.Text = "";
            mtxFromDate.Text = "";// _toDate.AddMonths(1).ToString("MM/yyyy");
            mtxToDate.Text = "";
            txtDateVal.Text = DateTime.Now.ToString("dd/MM/yyyy");
            timSoBHXH1.Focus();
            //
            LoadData();
        }

        private void timSoBHXH1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                timSoBHXH1.Validate();
            }
        }

        private void txtJob_Validated(object sender, EventArgs e)
        {
            btnSave.Select();
        }
    }
}
